<template>
  <div class="schedule-management">
    <div class="header">
      <h2>员工排班管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showOptimizationDialog = true">
          资源优化建议
        </el-button>
        <el-button type="success" @click="refreshData">
          刷新数据
        </el-button>
      </div>
    </div>

    <div class="content">
      <div class="sidebar">
        <div class="employee-list">
          <h3>员工列表</h3>
          <div class="employee-search">
            <el-input
              v-model="employeeSearchQuery"
              placeholder="搜索员工姓名、电话..."
              prefix-icon="el-icon-search"
              clearable
              size="small"
              @input="filterEmployees"
            />
          </div>
          <div class="employee-items" ref="employeeList">
            <div
              v-for="employee in displayedEmployees"
              :key="employee._id"
              class="employee-item"
              :class="{ active: selectedEmployee?._id === employee._id }"
              @click="selectEmployee(employee)"
              draggable="true"
              @dragstart="handleEmployeeDragStart($event, employee)"
              @dragend="handleEmployeeDragEnd"
            >
              <div class="employee-avatar">
                <img :src="employee.avatar || defaultAvatar" :alt="employee.username" />
              </div>
              <div class="employee-info">
                <div class="employee-name">{{ employee.username }}</div>
                <div class="employee-details">
                  <el-tag size="mini" type="info">
                    {{ employee.sex || '未知' }}
                  </el-tag>
                  <el-tag size="mini" type="info" v-if="employee.age">
                    {{ employee.age }}岁
                  </el-tag>
                </div>
                <div class="employee-contact">
                  <small>{{ employee.phone || '无电话' }}</small>
                </div>
                <div class="employee-status">
                  <el-tag
                    :type="employee.status ? 'success' : 'danger'"
                    size="mini"
                  >
                    {{ employee.status ? '启用' : '禁用' }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div v-if="filteredEmployees.length === 0" class="empty-result">
              <el-empty description="没有找到匹配的员工" :image-size="60" />
            </div>
          </div>
          <div class="list-stats">
            <small>共 {{ filteredEmployees.length }} 名员工</small>
          </div>
        </div>
      </div>

      <div class="calendar-container">
        <CustomCalendar
          :events="events"
          :employees="employees"
          @week-changed="handleWeekChanged"
          @event-updated="loadEvents"
          @event-created="loadEvents"
          @event-deleted="loadEvents"
          ref="customCalendar"
        />
      </div>
    </div>

    <!-- 事件详情弹窗 -->
    <el-dialog
      :title="eventDialogTitle"
      :visible.sync="eventDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="eventForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="eventForm.title" placeholder="请输入排班标题" />
        </el-form-item>
        <el-form-item label="员工">
          <el-select
            v-model="eventForm.technician"
            placeholder="选择员工"
            filterable
            :disabled="!hasEditPermission"
          >
            <el-option
              v-for="employee in employees"
              :key="employee._id"
              :label="employee.username"
              :value="employee._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="eventForm.start"
            type="datetime"
            placeholder="选择开始时间"
            :disabled="!hasEditPermission"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="eventForm.end"
            type="datetime"
            placeholder="选择结束时间"
            :disabled="!hasEditPermission"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker
            v-model="eventForm.color"
            :disabled="!hasEditPermission"
            :predefine="[
              '#3788d8',
              '#ff6b6b',
              '#4ecdc4',
              '#45b7d1',
              '#96ceb4',
              '#feca57',
              '#ff9ff3',
              '#54a0ff',
              '#5f27cd',
              '#00d2d3',
              '#ff9f43',
              '#10ac84'
            ]"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="eventForm.notes"
            type="textarea"
            :rows="3"
            placeholder="添加备注信息"
            :disabled="!hasEditPermission"
          />
        </el-form-item>
        <el-form-item label="状态" v-if="eventForm.id">
          <el-select
            v-model="eventForm.status"
            placeholder="选择状态"
            :disabled="!hasEditPermission"
          >
            <el-option label="已安排" value="scheduled" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="eventDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          @click="deleteEvent"
          v-if="eventForm.id && hasEditPermission"
        >
          删除
        </el-button>
        <el-button
          type="primary"
          @click="saveEvent"
          v-if="hasEditPermission"
        >
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 资源优化建议弹窗 -->
    <el-dialog
      title="资源优化建议"
      :visible.sync="showOptimizationDialog"
      width="700px"
    >
      <div v-if="optimizationData">
        <div class="optimization-summary">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-number">{{ optimizationData.totalTechnicians }}</div>
                <div class="stat-label">总员工数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-number">{{ optimizationData.totalDays }}</div>
                <div class="stat-label">总天数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-number">{{ optimizationData.schedules.length }}</div>
                <div class="stat-label">总排班数</div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <div class="suggestions-list">
          <h4>优化建议</h4>
          <div
            v-for="(suggestion, index) in optimizationData.suggestions"
            :key="index"
            class="suggestion-item"
            :class="suggestion.type"
          >
            <el-alert
              :title="suggestion.message"
              :type="suggestion.type === 'warning' ? 'warning' : 'info'"
              :closable="false"
              show-icon
            />
          </div>
        </div>
      </div>
      <div v-else class="loading">
        <el-loading text="正在分析数据..." />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CustomCalendar from './CustomCalendar.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'ScheduleManagement',
  components: {
    CustomCalendar
  },
  data() {
    return {
      employees: [],
      filteredEmployees: [],
      events: [],
      selectedEmployee: null,
      employeeSearchQuery: '',
      eventDialogVisible: false,
      showOptimizationDialog: false,
      eventForm: {
        id: null,
        title: '',
        technician: '',
        start: null,
        end: null,
        color: '#3788d8',
        notes: '',
        status: 'scheduled'
      },
      optimizationData: null,
      defaultAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      searchTimeout: null
    }
  },
  computed: {
    filteredEmployees() {
      if (!this.employeeSearchQuery) return this.employees
      const search = this.employeeSearchQuery.toLowerCase()
      return this.employees.filter(emp => 
        emp.username.toLowerCase().includes(search) ||
        (emp.phone && emp.phone.toLowerCase().includes(search))
      )
    },
    displayedEmployees() {
      // 虚拟列表优化：只显示可见区域的员工
      return this.filteredEmployees.slice(0, 100) // 限制显示数量提高性能
    },
    hasEditPermission() {
      const userRole = localStorage.getItem('userRole')
      return userRole === '老板' || userRole === '管理员'
    },
    eventDialogTitle() {
      return this.eventForm.id ? '编辑排班' : '创建排班'
    }
  },
  async mounted() {
    await this.loadEmployees()
    await this.loadEvents()
    this.updateCalendarPermissions()
  },
  methods: {
    async loadEmployees() {
      try {
        const params = {
          search: this.employeeSearchQuery,
          status: 'all' // 显示所有状态的员工
        }
        const response = await request.get('/api/schedules/technicians', { params })
        if (response.data.success) {
          this.employees = response.data.data
          this.filteredEmployees = [...this.employees] // 初始化筛选列表
          console.log('员工列表加载成功:', this.employees);
        }
      } catch (error) {
        ElMessage.error('加载员工列表失败')
        console.error(error)
      }
    },
    async loadEvents() {
      try {
        const now = new Date()
        const start = this.getWeekStart(now)
        const end = new Date(start)
        end.setDate(end.getDate() + 6)
        end.setHours(23, 59, 59, 999)

        const response = await request.get('/api/schedules/events', {
          params: {
            start: start.toISOString(),
            end: end.toISOString()
          }
        })
        
        if (response.data.success) {
          this.events = response.data.data
        }
      } catch (error) {
        ElMessage.error('加载排班数据失败')
        console.error(error)
      }
    },
    
    getWeekStart(date) {
      const d = new Date(date)
      const day = d.getDay()
      const diff = d.getDate() - day + (day === 0 ? -6 : 1)
      const weekStart = new Date(d.setDate(diff))
      weekStart.setHours(0, 0, 0, 0)
      return weekStart
    },
    updateCalendarPermissions() {
      // 权限逻辑交由 CustomCalendar 内部处理
    },
    
    async handleWeekChanged(weekStart) {
      try {
        const start = weekStart
        const end = new Date(start)
        end.setDate(end.getDate() + 6)
        end.setHours(23, 59, 59, 999)

        const response = await request.get('/api/schedules/events', {
          params: {
            start: start.toISOString(),
            end: end.toISOString()
          }
        })
        
        if (response.data.success) {
          this.events = response.data.data
        }
      } catch (error) {
        console.error('加载事件失败:', error)
      }
    },
    selectEmployee(employee) {
      this.selectedEmployee = employee
      // 筛选逻辑交由 CustomCalendar 内部处理
    },
    filterEmployees() {
      // 防抖处理，避免频繁搜索
      clearTimeout(this.searchTimeout)
      this.searchTimeout = setTimeout(() => {
        const query = this.employeeSearchQuery.toLowerCase().trim()
        if (!query) {
          this.filteredEmployees = [...this.employees]
        } else {
          this.filteredEmployees = this.employees.filter(emp => 
            emp.username.toLowerCase().includes(query) ||
            (emp.phone && emp.phone.toLowerCase().includes(query)) ||
            (emp.email && emp.email.toLowerCase().includes(query))
          )
        }
      }, 300)
    },
    filterCalendarByEmployee(employee) {
      // 筛选逻辑交由 CustomCalendar 内部处理
    },
    
    handleEmployeeDragStart(event, employee) {
      // 设置拖拽数据
      event.dataTransfer.setData('application/json', JSON.stringify({
        type: 'employee',
        employee: employee
      }))
      
      // 添加拖拽时的视觉反馈
      event.target.style.opacity = '0.5'
      event.target.style.cursor = 'grabbing'
    },
    
    handleEmployeeDragEnd(event) {
      // 恢复拖拽元素的样式
      event.target.style.opacity = ''
      event.target.style.cursor = ''
    },
    async saveEvent() {
      try {
        if (!this.eventForm.technician) {
          ElMessage.warning('请选择员工')
          return
        }

        if (this.eventForm.start >= this.eventForm.end) {
          ElMessage.warning('结束时间必须晚于开始时间')
          return
        }

        const formData = {
          title: this.eventForm.title,
          technician: this.eventForm.technician,
          start: this.eventForm.start,
          end: this.eventForm.end,
          color: this.eventForm.color,
          notes: this.eventForm.notes,
          status: this.eventForm.status
        }

        if (this.eventForm.id) {
          await request.put(`/api/schedules/events/${this.eventForm.id}`, formData)
          ElMessage.success('排班更新成功')
        } else {
          await request.post('/api/schedules/events', formData)
          ElMessage.success('排班创建成功')
        }

        this.eventDialogVisible = false
        await this.loadEvents()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    },
    async deleteEvent() {
      try {
        await ElMessageBox.confirm('确定要删除这个排班吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await request.delete(`/api/schedules/events/${this.eventForm.id}`)
        ElMessage.success('排班删除成功')
        this.eventDialogVisible = false
        await this.loadEvents()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    },
    async loadOptimizationData() {
      if (!this.showOptimizationDialog) return

      try {
        const calendarApi = this.$refs.fullCalendar.getApi()
        const start = calendarApi.view.activeStart
        const end = calendarApi.view.activeEnd

        const response = await request.get('/api/schedules/optimization-suggestions', {
          params: { start: start.toISOString(), end: end.toISOString() }
        })

        if (response.data.success) {
          this.optimizationData = response.data.data
        }
      } catch (error) {
        ElMessage.error('获取优化建议失败')
        console.error(error)
      }
    },
    async refreshData() {
      await this.loadEmployees()
      await this.loadEvents()
      ElMessage.success('数据已刷新')
    },
    beforeUnmount() {
      // 清理定时器
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
    },
    getStatusType(status) {
      const statusMap = {
        '空闲中': 'success',
        '服务中': 'warning',
        '休息中': 'info',
        '请假中': 'danger'
      }
      return statusMap[status] || 'info'
    }
  },
  watch: {
    showOptimizationDialog(newVal) {
      if (newVal) {
        this.loadOptimizationData()
      }
    }
  }
}
</script>

<style scoped>
.schedule-management {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 350px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.employee-list {
  padding: 20px;
}

.employee-list h3 {
  margin: 0 0 15px 0;
  color: #303133;
}

.employee-search {
  margin-bottom: 15px;
}

.employee-items {
  max-height: calc(100vh - 200px);
  height:60vh;
  overflow-y: auto;
}

.employee-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.employee-item:hover {
  background: #f5f7fa;
}

.employee-item.active {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
}

.employee-item.dragging {
  opacity: 0.5;
  cursor: grabbing;
  transform: rotate(5deg);
}

.employee-avatar {
  width: 50px;
  height: 50px;
  margin-right: 12px;
}

.employee-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.employee-info {
  flex: 1;
}

.employee-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.employee-skills {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 4px;
}

.employee-status {
  font-size: 12px;
}

.calendar-container {
  flex: 1;
  padding: 20px;
  background: #fff;
  overflow: auto;
}

.optimization-summary {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.suggestions-list {
  margin-top: 20px;
}

.suggestions-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.suggestion-item {
  margin-bottom: 10px;
}

.loading {
  text-align: center;
  padding: 40px;
}

.search-box {
  margin-bottom: 15px;
}

.employee-items::-webkit-scrollbar {
  width: 4px;
}

.employee-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.employee-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.employee-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.empty-result {
  padding: 40px 0;
  text-align: center;
}

.list-stats {
  margin-top: 15px;
  text-align: center;
  color: #666;
  font-size: 12px;
}
</style>